<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/7/1 9:35
 * Modified Time: 2019/7/1 9:35
 * Version: 2.0
 */

namespace App\Modules\MemberCard\Services;


use App\Exceptions\AllValidatorException;
use App\Exceptions\DbException;
use App\Lib\CreateStaticNumber;
use App\Lib\Facades\FLAuth;
use App\Lib\File\AliOSS;
use App\Lib\Utilities;
use App\Models\MemberCard;
use App\Modules\Cashier\Repositories\BillRepository;
use App\Modules\Employee\Repositories\EmployeeRepository;
use App\Modules\MemberCard\Criterias\AppGetCardTypeListCriteria;
use App\Modules\MemberCard\Criterias\AppGetMemberCard;
use App\Modules\MemberCard\Criterias\AppGetMemberCardFlowCriteria;
use App\Modules\MemberCard\Criterias\AppGetMemberCardListCriteria;
use App\Modules\MemberCard\Criterias\AppGetMemberCardListServiceCriteria;
use App\Modules\MemberCard\Criterias\BackupCriteria;
use App\Modules\MemberCard\Criterias\GetCardTypeByIdCriteria;
use App\Modules\MemberCard\Criterias\GetCardTypeService;
use App\Modules\MemberCard\Criterias\GetMemberCardByCardTypeCriteria;
use App\Modules\MemberCard\Criterias\GetMyMemberCardListCriteria;
use App\Modules\MemberCard\Criterias\GetMyReceiveMemberCardListCriteria;
use App\Modules\MemberCard\Criterias\GetNotAuditedMemberCardCriteria;
use App\Modules\MemberCard\Criterias\GetTransferMemberCardListCriteria;
use App\Modules\MemberCard\Criterias\WxGetMemberCardInfo;
use App\Modules\MemberCard\Repositores\BackupRepository;
use App\Modules\MemberCard\Repositores\CardTypeRepository;
use App\Modules\MemberCard\Repositores\MemberCardFlowRepository;
use App\Modules\MemberCard\Repositores\MemberCardOrderRepository;
use App\Modules\MemberCard\Repositores\MemberCardRepository;
use App\Modules\Message\Repositories\MessageRepository;
use App\Modules\Order\Repositories\RoyaltyRepository;
use App\Modules\Order\Services\OrderService;
use App\Modules\Service\Repositories\CardTypeServiceRepository;
use App\Modules\Service\Repositories\ServiceRepository;
use App\Modules\Store\Repositories\StoreRepository;
use App\Modules\System\Repositories\AmountFlowRepository;
use App\Modules\System\Repositories\UserStoreRepository;
use Flower\Core\Repository\Eloquent\BaseService;
use Flower\Core\Repository\Exceptions\ValidatorException;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\MessageBag;
use mysql_xdevapi\Exception;
use Maatwebsite\Excel\Facades\Excel;

class MemberCardService extends BaseService
{
	use DispatchesJobs;

	private $cardTypeRepository;
	private $userStoreRepository;
	private $cardTypeServiceRepository;
	private $memberCardRepository;
	private $backupRepository;
	private $royaltyRepository;
	private $storeRepository;
	private $employeeRepository;
	private $messageRepository;
	private $amountFlowRepository;
	private $memberCardFlowRepository;
	private $billRepository;
	private $memberCardOrderRepository;

	public function __construct(CardTypeRepository $cardTypeRepository,
	                            UserStoreRepository $userStoreRepository,
	                            CardTypeServiceRepository $cardTypeServiceRepository,
	                            MemberCardFlowRepository $memberCardFlowRepository,
	                            BackupRepository $backupRepository,
	                            RoyaltyRepository $royaltyRepository,
	                            StoreRepository $storeRepository,
	                            EmployeeRepository $employeeRepository,
	                            MessageRepository $messageRepository,
	                            AmountFlowRepository $amountFlowRepository,
	                            MemberCardRepository $memberCardRepository,
	                            BillRepository $billRepository,
	                            MemberCardOrderRepository $memberCardOrderRepository
	)
	{
		$this->cardTypeRepository = $cardTypeRepository;
		$this->userStoreRepository = $userStoreRepository;
		$this->memberCardRepository = $memberCardRepository;
		$this->cardTypeServiceRepository = $cardTypeServiceRepository;
		$this->backupRepository = $backupRepository;
		$this->royaltyRepository = $royaltyRepository;
		$this->storeRepository = $storeRepository;
		$this->employeeRepository = $employeeRepository;
		$this->messageRepository = $messageRepository;
		$this->amountFlowRepository = $amountFlowRepository;
		$this->memberCardFlowRepository = $memberCardFlowRepository;
		$this->billRepository = $billRepository;
		$this->memberCardOrderRepository = $memberCardOrderRepository;
	}

	/*
	 * 用户申请会员卡
	 */
	public function applyMemberCard($member_id, $type_id, $code, $name, $mobile, $sex, $user_id)
	{

		if (!Utilities::checkSmsCode($mobile, 4, $code)) {
			throw new AllValidatorException(['msg' => '验证码错误']);
		}

		//获取会员卡类实例
		$card_type = $this->cardTypeRepository->find($type_id);

		if (!$card_type) {
			throw new AllValidatorException(['msg' => '会员卡类不存在']);

		}
		$store_id = $card_type->store_id;

		if ($card_type->category == 1) {
			$attribute = 1;
		} else {
			$attribute = 2;
		}
		$count = 0;
		$balance = 0;
		$num = time();
		return $this->memberCardRepository
			->createMemberCard($store_id,
				$type_id,
				$name,
				$mobile,
				$sex,
				$attribute,
				$count,
				$balance,
				0,
				$user_id,
				$member_id,
				$num,
				1
			);
	}

	/*
	 * 获取本店所有会员卡-分页
	 */
	public function getMemberCardListPage($store_id, $status, $keywords, $pageSize)
	{

		$member_card_list = $this
			->memberCardRepository
			->pushCriteria(new AppGetMemberCardListCriteria($store_id, $status, null, $keywords))
			->paginate($pageSize, ['*'], 'paginate');

		$member_card_list = Utilities::dealPage($member_card_list);
		return $member_card_list;
	}

	/*
	 * 获取本店所有会员卡-分页
	 */
	public function getMemberCardListPageService($store_id, $status, $keywords, $pageSize, $service_id)
	{

		$member_card_list = $this
			->memberCardRepository
			->pushCriteria(new AppGetMemberCardListServiceCriteria($store_id, $status, null, $keywords, $service_id))
			->paginate($pageSize, ['*'], 'paginate');

		$member_card_list = Utilities::dealPage($member_card_list);
		return $member_card_list;
	}

	/**
	 * 理发师手动添加会员卡
	 * @param $store_id
	 * @param $type_id
	 * @param $name
	 * @param $mobile
	 * @param $sex
	 * @param null $code
	 * @return mixed
	 * @throws AllValidatorException
	 */
	public function createMemberCard($store_id, $type_id, $name, $mobile, $sex, $code = null)
	{

		//获取卡类
		$card_type = $this->cardTypeRepository->find($type_id);

		if (!$card_type) {
			throw new AllValidatorException(['msg' => '卡类不存在']);
		} else {
			if ($card_type->store_id != $store_id) {
				throw new AllValidatorException(['msg' => '卡类不存在']);
			}
		}

		$attribute = $card_type->category;
		$count = 0;
		$balance = 0;
		$user_id = FLAuth::id();
		$num = CreateStaticNumber::makeNo('card');
		$member_card = $this->memberCardRepository->createMemberCard($store_id, $type_id, $name, $mobile, $sex, $attribute, $count, $balance, 0, $user_id, 0, $num, 4);
		return $this->getMemberCard($member_card->id);
	}

	/**
	 * 转移会员卡
	 * @param $store_id
	 * @param $card_type_id
	 * @param $name
	 * @param $mobile
	 * @param $sex
	 * @param $amount
	 * @throws AllValidatorException
	 */
	public function transferMemberCard($store_id, $card_type_id, $name, $mobile, $sex, $amount)
	{
		DB::beginTransaction();
		try {
			//获取卡类
			$card_type = $this->cardTypeRepository->find($card_type_id);

			if (!$card_type) {
				throw new AllValidatorException(['msg' => '卡类不存在']);
			} else {
				if ($card_type->store_id != $store_id) {
					throw new AllValidatorException(['msg' => '卡类不存在']);
				}
			}
			$attribute = $card_type->category;
			if ($attribute == 1) {
				$count = $amount;
				$balance = $amount * $card_type->unit_price;
			} else {
				$count = 0;
				$balance = $amount;
			}
			$user_id = FLAuth::id();
			$num = CreateStaticNumber::makeNo('card');

			$member_card = $this->memberCardRepository->createMemberCard($store_id, $card_type_id, $name, $mobile, $sex, $attribute, $count, $balance, 1, $user_id, 0, $num, 2);

			$member_card_flow = $this->memberCardFlowRepository->transfer($member_card->id, $store_id, $attribute, $user_id, $count, $balance);

//            $this->amountFlowRepository->add($store_id,$user_id,2,$member_card_flow->id,$balance,0,0,0,0,0,0,0);
			return DB::commit();
		} catch (AllValidatorException $exception) {
			DB::rollBack();
			throw new AllValidatorException(['msg' => $exception->msg]);
		}
	}

	/**
	 * 获取转移会员卡历史
	 * @param $store_id
	 * @param $pageSize
	 * @return array|mixed
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 */
	public function getTransferMemberCardList($store_id, $pageSize, $keywords)
	{
		$data = $this->memberCardRepository
			->pushCriteria(new GetTransferMemberCardListCriteria($store_id, $keywords))
			->paginate($pageSize, ['*']);
		$data = Utilities::dealPage($data);
		return $data;
	}

	/**
	 * 删除转移会员卡
	 * @param $member_card_id
	 * @return int
	 * @throws AllValidatorException
	 */
	public function delTransferMemberCard($member_card_id)
	{
		//获取会员卡实例
		$member_card = $this->memberCardRepository->isExisted($member_card_id);

		if ($member_card->member_id != 0) {
			throw new AllValidatorException(['msg' => '该卡已被领取不可删除']);
		}

		return $this->memberCardRepository->delete($member_card_id);

	}

	/**
	 * 编辑转移会员卡
	 * @param $member_card_id
	 * @param $card_type_id
	 * @param $name
	 * @param $mobile
	 * @param $sex
	 * @param $amount
	 * @return mixed
	 * @throws AllValidatorException
	 * @throws \App\Exceptions\NotFoundException
	 */
	public function editTransferMemberCard($member_card_id, $card_type_id, $name, $mobile, $sex, $amount)
	{
		//获取会员卡实例
		$member_card = $this->memberCardRepository->isExisted($member_card_id);

		if ($member_card->member_id != 0) {
			throw new AllValidatorException(['msg' => '该卡已被领取不可编辑']);
		}

		if ($card_type_id) {
			//获取卡类
			$card_type = $this->cardTypeRepository->find($card_type_id);

			if (!$card_type) {
				throw new AllValidatorException(['msg' => '卡类不存在']);
			}
			$attribute = $card_type->category;
			if ($attribute == 1) {
				$count = $amount;
				$balance = $amount * $card_type->unit_price;
			} else {
				$count = 0;
				$balance = $amount;
			}
		} else {
			$card_type_id = $member_card->type_id;
			//获取卡类
			$card_type = $this->cardTypeRepository->find($card_type_id);

			if (!$card_type) {
				throw new AllValidatorException(['msg' => '卡类不存在']);
			}
			$attribute = $card_type->category;
			if ($attribute == 1) {
				$count = $amount;
				$balance = $amount * $card_type->unit_price;
			} else {
				$count = 0;
				$balance = $amount;
			}
		}


		return $this->memberCardRepository->editTransferMemberCard($member_card_id, $card_type_id, $name, $mobile, $sex, $attribute, $count, $balance);
	}


	/**
	 * 审核会员卡
	 * @param $user_id
	 * @param $member_card_id
	 * @param $operation
	 * @param $real_amount
	 * @param $payment
	 * @param $present
	 * @param $assistant_id
	 * @return array
	 * @throws AllValidatorException
	 * @throws \App\Exceptions\NotFoundException
	 */
	public function examineMemberCard($billId, $operation, $real_amount, $payment, $present)
	{
		$billInfo = $this->billRepository->isExited($billId);
		$memberCardOrderInfo = $this->memberCardOrderRepository->isExited($billInfo->order_id);
		$member_card = $this->memberCardRepository->find($memberCardOrderInfo->member_id);
		if (!$member_card) {
			throw new AllValidatorException(['msg' => '会员不存在']);
		}
		if ($member_card->status == 1) {
			throw new AllValidatorException(['msg' => '请勿重复审核']);
		}

		$card_type = $this->cardTypeRepository->find($member_card->type_id);

		//判断实付金额
		if ($card_type->category == 1) {
			$count = floor($real_amount / $card_type->unit_price);
			$balance = $real_amount;
		} else {
			$count = 0;
			if ($card_type->discount_way == 1) {      //判断是否是赠额卡
				if ($real_amount != $card_type->price) { //判断实付金额与首充金额是否相等
					if ($present !== null) {        //判断有没有修改赠额
						$balance = $real_amount + $present;
					} else {
						$balance = $real_amount;
						//根据id获取会员卡实例

					}
				} else {
					if ($present !== null) {
						$balance = $card_type->price + $present;
					} else {
						$balance = $real_amount + $card_type->present;
					}
				}
			} else {
				$balance = $real_amount;
			}
		}
//	    $user_id,$operation,$balance,$count,$payment)
		return compact('member_card', 'operation', 'balance', 'count', 'real_amount', 'payment');
//        DB::beginTransaction();
//        try {
//            //更改会员卡状态
//            $this->memberCardRepository->examineMemberCard($member_card_id, $operation, $user_id);
//            if ($operation == 1) {
//                //获取卡类
//                $card_type_id = $member_card->type_id;
//                $card_type = $this->cardTypeRepository->find($card_type_id);
//
//                $member_id = $member_card->member_id;
//                $store_id = $member_card->store_id;
//                $category = $member_card->attribute;
//                //会员卡金额添加
//                $this->memberCardRepository->recharge($member_card_id, $balance, $count);
//                //会员卡开卡记录添加
//                $member_card_flow = $this->memberCardFlowRepository->init($member_card_id, $member_id, $store_id, $category, $user_id, $count, $balance, $real_amount, $payment);
//
//                //加提成
//                $royalty = round(($card_type->royalty/100)*$real_amount,2);
//                $this->royaltyRepository->createRoyalty($user_id, $store_id, 2, $member_card_flow->id, $real_amount, 0, $royalty);
//
//                //加流水
//                $profit = $real_amount - $royalty;
//                $this->amountFlowRepository->add($store_id,$user_id,2,$member_card_flow->id,$card_type->price,$real_amount,$profit,0,$royalty,0,0,$payment);
//
//                //发消息
//                $this->messageCardNotice($store_id, $member_card, $user_id);
//            }
//
//            DB::commit();
//            return $member_card;
//        } catch (AllValidatorException $allValidatorException) {
//            DB::rollBack();
//            throw new AllValidatorException(['msg' => $allValidatorException->msg]);
//        }

	}


	public function getStoreMemberCradNum($store_id, $status, $user_id)
	{
		return $this->memberCardRepository->getStoreMemberCradNum($store_id, $status, $user_id)->count();
	}


//	/**
//	 * 会员卡充值
//	 * @param $member_card_id
//	 * @param $recharge_num
//	 * @param $payment
//	 * @return bool
//	 * @throws \App\Exceptions\NotFoundException
//	 */
//    public function rechargeMemberCard_bak($member_card_id, $recharge_num, $payment)
//    {
//        $user_id = FLAuth::id();
//
//        //获取会员卡实例
//        $memberCardInfo = $this->memberCardRepository->isExisted($member_card_id);
//
//        $cardType = $this->cardTypeRepository->isExisted($memberCardInfo->type_id);
//
//        $flowNums = 0;
//        DB::beginTransaction();
//
//        if ($memberCardInfo->attribute == 1) {
//            $memberCardInfo->count += $cardType->count;
//            $flowNums = $cardType->count;
//        } else {
//            $memberCardInfo->balance += $cardType->price;
//            $flowNums = $cardType->price;
//        }
//
//        $memberCardInfo->save();
//
//        $cardFlow = $this->memberCardFlowRepository->addFlowMemberCard($cardType->category, $member_card_id, $memberCardInfo->member_id, $memberCardInfo->user_id, $memberCardInfo->store_id, config('constant.memberCard.type.recharge'), 0, $flowNums, $recharge_num);
//        $flag = empty($cardFlow);
//
//        !$flag ? DB::commit() : DB::rollBack();
//
//
//        return !$flag;
//    }


	/**
	 * 充值会员卡
	 * @param $user_id
	 * @param $member_card_id
	 * @param $recharge_num
	 * @param $payment
	 * @param $real_amount
	 * @param $present
	 * @param $assistant_id
	 * @return array
	 * @throws ValidatorException
	 * @throws \App\Exceptions\NotFoundException
	 */
	public function rechargeMemberCard($billId, $recharge_num, $payment, $real_amount, $present)
	{
		$billInfo = $this->billRepository->isExited($billId);
		$memberCardOrderInfo = $this->memberCardOrderRepository->isExited($billInfo->order_id);
		//获取会员卡实例
		$member_card = $this->memberCardRepository->isExisted($memberCardOrderInfo->member_id);
		$card_type = $this->cardTypeRepository->isExisted($member_card->type_id);
		//处理充值数据
		$recharge_data = $this->dealRechargeData($member_card, $real_amount, $present);

		$count = $recharge_data['count'];
		$balance = $recharge_data['balance'];
		return compact('member_card', 'balance', 'real_amount', 'count', 'payment', 'card_type');
//        DB::beginTransaction();
//        try {
//            //加钱
//            $this->memberCardRepository->recharge($member_card_id, $balance, $count);
//            //创建充值记录
//            $member_card_flow = $this->memberCardFlowRepository
//                ->recharge($member_card_id,
//                    $member_card->member_id,
//                    $member_card->store_id,
//                    $member_card->attribute,
//                    $user_id,
//                    $count,
//                    $balance,
//                    $real_amount,
//                    $payment);
//
//            $store_id = $member_card->store_id;
//            //加资金流水
//            $this->amountFlowRepository->add($store_id,$user_id,2,$member_card_flow->id,$card_type->price,$real_amount,$real_amount,0,0,0,0,$payment);
//
//
//            DB::commit();
//            //发消息
//            $store_name = $this->storeRepository->getStoreNameById($store_id)->store_name;
//
//            $contentCate = $member_card->attribute == 1 ? ',会员卡可用次数为：' . $member_card->count . '次' : ',会员卡余额为：' . $member_card->balance . '元';
//            $card_type_id = $member_card->type_id;
//            $card_type_name = $this->cardTypeRepository->find($card_type_id)->name;
//            $barber_name = $this->employeeRepository->find($user_id)->nick;
//            $type = config('constant.message.sub_type.card_recharge');
//
//            if ($member_card->member_id) {
//                $scene = config('constant.message.scene.wx');
//                $content = '您在' . $store_name . '店，给会员卡号为：' . $member_card->card_num . '成功充值' . $real_amount . $contentCate;
//                $noticeFace = config('constant.message.wx_image');
//                $noticeTitle = $store_name;
//                $noticeTitleRight = '';
//                $contentLeft = $card_type_name;
//                $contentRight = null;
//                $datas = $this->messageRepository->makeMessageData($scene, $type, $noticeFace, $noticeTitle, $noticeTitleRight, $contentLeft, $contentRight, $content, $member_card->id);
//                $this->messageRepository->addMessage($member_card->member_id, $datas, $member_card->store_id);
//            }
//            $sceneApp = config('constant.message.scene.app');
//            $contentApp = '会员' . $member_card->name . '在您的' . $store_name . '店成功充值' . $real_amount;
//            $noticeFaceApp = config('constant.message.wx_image');
//            $noticeTitleApp = $member_card->name;
//            $noticeTitleRightApp = $store_name;
//            $contentLeftApp = $card_type_name;
//            $contentRightApp = "办理人：" . $barber_name;
//            $datasApp = $this->messageRepository->makeMessageData($sceneApp, $type, $noticeFaceApp, $noticeTitleApp, $noticeTitleRightApp, $contentLeftApp, $contentRightApp, $contentApp, $member_card->id);
//            $this->messageRepository->sendBossMessage(config('constant.role.manager'), $member_card->store_id, $datasApp, $user_id);
//            return true;
//        } catch (AllValidatorException $e) {
//            DB::rollBack();
//            throw new AllValidatorException(['msg' => $e->msg]);
//        }
	}

	/*
	* 处理充值数据
	*/
	protected function dealRechargeData($member_card, $real_amount, $present)
	{
		//获取会员卡类实例
		$card_type_id = $member_card->type_id;
		$card_type = $this->cardTypeRepository->findByField('id', $card_type_id)->first();

		if (!$card_type) {
			throw new ValidatorException(new MessageBag(['会员卡类不存在']));
		}

		//判断充值数
		if ($member_card->attribute == 1) {
			$count = floor($real_amount / $card_type->unit_price);

			$update_data = [
				'count'   => $count,
				'balance' => $real_amount,
			];
		} else {
			if ($card_type->discount_way == 1) {      //判断是否是赠额卡
				if ($real_amount != $card_type->price) { //判断实付金额与首充金额是否相等
					if ($present !== null) {        //判断有没有修改赠额
						$balance = $real_amount + $present;
					} else {
						$balance = $real_amount;
					}
				} else {
					if ($present !== null) {
						$balance = $card_type->price + $present;
					} else {
						$balance = $real_amount + $card_type->present;
					}
				}
			} else {
				$balance = $real_amount;
			}

			$update_data = [
				'balance' => $balance,
				'count'   => 0
			];
		}

		return $update_data;
	}


	/*
	 * 小程序用户获取个人会员卡列表
	 */
	public function getMyMemberCardList($pageSize)
	{
		$list = $this->memberCardRepository->pushCriteria(new GetMyMemberCardListCriteria())->paginate($pageSize, ['*'], 'paginate');

		$list = Utilities::dealPage($list);
		return $list;
	}

	/**
	 * 理发师获取本人未审核会员卡
	 * @param $user_id
	 * @param $store_id
	 * @param $pageSize
	 * @param $keywords
	 * @return array|mixed
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 */
	public function getNotAuditedMemberCard($user_id, $store_id, $status, $pageSize, $keywords)
	{
		$list = $this->memberCardRepository->pushCriteria(new GetNotAuditedMemberCardCriteria($user_id, $store_id, $status, $keywords))->paginate($pageSize, ['*'], 'paginate');

		$list = Utilities::dealPage($list);
		return $list;
	}

	/*
	 * 获取会员卡详细信息
	 */
	public function getMemberCardInfo($member_card_id)
	{
		$info = $this->memberCardRepository->pushCriteria(new WxGetMemberCardInfo($member_card_id))->first();
		return $info;
	}

	/*
	 * 获取会员卡详细信息
	 */
	public function getMemberCard($member_card_id)
	{
		$info = $this->memberCardRepository->pushCriteria(new AppGetMemberCard($member_card_id))->first();

		return $info;
	}

	/*
	 * 获取会员卡关联服务
	 */
	public function getMemberCardServiceList($card_type_id)
	{
		$list = $this->cardTypeRepository->pushCriteria(new GetCardTypeService($card_type_id))->get();

		return $list;
	}

	/**
	 * 小程序获取本人领取会员卡
	 * @param $phone
	 * @param $code
	 * @param $pageSize
	 * @return array|mixed
	 * @throws AllValidatorException
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 */
	public function getMyReceiveMemberCardList($phone, $code, $pageSize)
	{

		$check_sms = Utilities::checkSmsCode($phone, 1, $code);

		if (!$check_sms) {
			throw new AllValidatorException(['msg' => '验证码错误']);
		}
		$list = $this->memberCardRepository
			->pushCriteria(new GetMyReceiveMemberCardListCriteria($phone))
			->paginate($pageSize, ['*']);
		$list = Utilities::dealPage($list);
		return $list;
	}

	/**
	 * 领取会员卡
	 * @param $member_card_id
	 * @return mixed
	 * @throws AllValidatorException
	 */
	public function receiveMemberCard($member_card_id)
	{
		//判断会员卡是否存在
		$member_card = $this->memberCardRepository->findByField(['id' => $member_card_id, 'member_id' => 0])->first();

		if (!$member_card) {
			throw new AllValidatorException(['msg' => '会员卡不存在或已被领取']);
		}
		$member_id = FLAuth::id();

		return $this->memberCardRepository->receiveMemberCard($member_id, $member_card_id);
	}


	/**
	 * 今日新增会员卡
	 * @param $request
	 * @return mixed
	 */
	public function statisticsMemberCard($request)
	{
		return $this->memberCardRepository->statisticsMemberCard($request);
	}

	/**
	 * 查询某店某天的会员卡数据
	 * @param $storeId
	 * @param int $userId
	 * @param $date
	 * @return array
	 */
	public function getDayMemberCard($storeId, $userId, $date)
	{
		// userId 为空查询某店  否则查询某理发师的
		return $this->memberCardRepository->increaseCards($storeId, $userId, $date);
	}


	public function getMemberCardSaleAmount($storeId, $userId)
	{
		return $this->memberCardFlowRepository->getMemberCardSaleAmount($storeId, $userId);
	}

	/**
	 * 会员卡消费
	 * @param $card_num
	 * @param $member_id
	 * @param $user_id
	 * @param $amount
	 * @throws AllValidatorException
	 */
	public function memberCardConsumption($card_num, $member_id, $user_id, $amount)
	{
		//获取会员卡
		$member_card = $this->memberCardRepository->getMemberCardByNum($card_num);

		$card_type_id = $member_card->type_id;
		$member_card_id = $member_card->id;
		//获取会员卡类
		$card_type = $this->cardTypeRepository->find($card_type_id)->first();
		$store_id = $card_type->store_id;
		$category = $card_type->category;

		DB::beginTransaction();

		try {
			$this->memberCardRepository->consumption($member_card_id, $amount);
			$this->memberCardFlowRepository
				->consumption($member_card_id, $member_id, $store_id, $category, $user_id, $amount);

			DB::commit();
		} catch (\Exception $exception) {
			DB::rollBack();
			throw new DbException();
		}

	}

	/**
	 * 获取会员卡交易记录
	 * @param $member_card_id
	 * @param $pageSize
	 * @return array
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 */
	public function getMemberCardFlow($member_card_id, $pageSize)
	{
		$data = $this->memberCardFlowRepository
			->pushCriteria(new AppGetMemberCardFlowCriteria($member_card_id))
			->paginate($pageSize, ['*']);
//        $cardInfo = $this->getMemberCard($member_card_id);
		$result = Utilities::dealPage($data);
//        $result['card_info'] = $cardInfo;
		return $result;
	}


	public function getMemberCardFlowNew($member_card_id, $pageSize)
	{
		$data = $this->memberCardFlowRepository
			->pushCriteria(new AppGetMemberCardFlowCriteria($member_card_id))
			->paginate($pageSize, ['*']);
		$result = Utilities::dealPage($data);
		$result['items'] = array_map(function ($v) {
			$newV['price'] = $v['type'] == 3 ? '-' . $v['balance'] : '+' . $v['balance'];
			$newV['created_at'] = $v['created_at'];
			if ($v['type'] == 3 && !empty($v['order']['items'])) {
				foreach ($v['order']['items'] as $sv) {
					$newV['list'][] = [
						'consumption_name' => $sv['service_name'],
						'barber_name'      => isset($sv['barber']['nick']) ? $sv['barber']['nick'] : '',
						'assistant_name'   => isset($sv['assistant']['nick']) ? $sv['barber']['nick'] : '',
						'count'            => isset($sv['count']) ? $sv['count'] : 1,
					];
				}
			} else {
				$newV['list'][] = [
					'consumption_name' => $v['type'] == 1 ? '开卡' : '充值',
					'barber_name'      => '',
					'assistant_name'   => '',
					'count'            => '',
				];
			}
			return $newV;
		}, $result['items']);
		$cardInfo = $this->getMemberCard($member_card_id);
		$result['card_info'] = [
			'member_card_id'        => isset($cardInfo->id) ? $cardInfo->id : 0,
			'member_face'           => isset($cardInfo->member->face) ? $cardInfo->member->face : '',
			'member_card_type_name' => isset($cardInfo->cardType->name) ? $cardInfo->cardType->name : '',
			'member_name'           => isset($cardInfo->name) ? $cardInfo->name : '',
			'member_balance'        => isset($cardInfo->balance) ? $cardInfo->balance : '',
		];
		return $result;
	}


	public function backupsMemberCard($user_id, $store_id)
	{
		//获取会员卡信息
		$member_card_list = $this->getMemberCardListPage($store_id, 1, null, null, 10000000);
		$count = $member_card_list['total'];
		$member_card_list = $member_card_list['items'];

		$cellData = [];
		$cellData[] = ['会员卡名', '卡类型', '卡号', '会员名', '手机号', '性别', '余额'];
		$name = iconv('UTF-8', 'GBK', md5($store_id . time()));
		foreach ($member_card_list as $key => $value) {
			$cellData[] = [
				$value['card_type']['name'],
				$value['attribute'] == 1 ? '次数卡' : '充值卡',
				$value['card_num'],
				$value['name'],
				$value['mobile'],
				$value['sex'] == 1 ? '男' : '女',
				$value['attribute'] == 1 ? $value['count'] . '次' : $value['balance'] . '元'
			];
		}

		Excel::create($name, function ($excel) use ($cellData) {
			$excel->sheet('score', function ($sheet) use ($cellData) {
				$sheet->rows($cellData);
			});
		})->store('xls');

		$oss = new AliOSS();
		$file = $oss->uploadByPath(storage_path() . '/exports/' . $name . '.xls', 'Excel', $name, 'xls');

//        copy(storage_path() . '/exports/' . $name . '.xls', storage_path() . '/app/public/' . $name . '.xls');
		unlink(storage_path() . '/exports/' . $name . '.xls');
		$backup_name = $this->backupRepository->backupName($store_id);
		$this->backupRepository->createBackup($store_id, $user_id, $count, $backup_name);


		return $file['ossName'];

	}

	public function getBackupsMemberCard($store_id, $pageSize)
	{
		$list = $this
			->backupRepository
			->pushCriteria(new BackupCriteria($store_id))
			->paginate($pageSize, ['*']);

		return Utilities::dealPage($list);

	}

	public function deleteMemberCard($store_id, $member_card_id)
	{
		//判断会员卡余额
		$member_card = $this->memberCardRepository->find($member_card_id);
		if (!$member_card) {
			throw new AllValidatorException(['msg' => '未找到该会员卡']);
		}
		$balance = $member_card->balance;
		if ($balance > 0) {
			throw new AllValidatorException(['msg' => '该卡仍有余额，不可删除。']);
		}
		return $member_card->delete();
	}
}